<?php


namespace app\admin\controller;

use app\common\model\User as UserModel;
use app\common\model\Role as RoleModel;
use app\common\model\UserRole as UserRole;
use think\Db;
use think\Exception;

class User extends BaseController
{
    // add
    public function add()
    {
        if ($this->request->isAjax() && $this->request->isPost()) {
            $post = $this->request->post();
            $user = new UserModel();

            // 判重
            $one = $user->where('username', $post['username'])->find();
            if ($one) {
                return mkRestful(1, '用户名已存在');
            }

            // post role id array
            $roleIdArr = [];
            if (isset($post['role_id'])) {
                $roleIdArr = array_keys($post['role_id']);
                unset($post['role_id']);
            }

            $post['password'] = sha1($post['password']);

            Db::startTrans();
            try{
                // 用户
                $result = $user->save($post);
                // 用户角色
                $user->roles()->attach($roleIdArr);
                Db::commit();
                $return = mkRestful(0, '用户添加成功', 'success');
            } catch (Exception $e) {
                Db::rollback();
                $return = mkRestful(1, $e->getMessage());
            }
            return $return;
        }
        $roles = RoleModel::where('disabled', 2)->select();
        $this->assign([
           'title' => '添加用户',
            'roles' => $roles
        ]);
        return $this->fetch();
    }

    // del
    public function del($model = null)
    {
        if (!$this->request->isDelete() || !$this->request->isAjax()) {
            return mkRestful(-1, '非法操作');
        }
        $ids = $this->request->delete('ids');
        Db::startTrans();
        try{
            $result = UserModel::destroy($ids);
            UserRole::where('user_id', 'in', $ids)->delete();
            Db::commit();
            $return = mkRestful(0, '成功删除'.$result.'个用户', 'success');
        } catch (Exception $e) {
            Db::rollback();
            $return = mkRestful(1, $e->getMessage());
        }

        return $return;
    }
    // edit
    public function edit()
    {
        $id = $this->request->param('id');
        $user = UserModel::with('roles')->find($id);
        if ($this->request->isAjax() && $this->request->isPost()) {
            $post = $this->request->post();
            // 密码处理
            if ($post['password']) {
                $post['password'] = sha1($post['password']);
            } else {
                unset($post['password']);
            }
            // post过来的role id
            $postRoleIdArr = [];
            if (isset($post['role_id'])) {
                $postRoleIdArr = array_keys($post['role_id']);
                unset($post['role_id']);
            }
            // 已存在的role id
            $roleIdArr = [];
            foreach ($user['roles'] as $role) {
                $roleIdArr[] = $role['id'];
            }
            // 数组差集区分新增的角色与删除的角色
            $addRole = array_diff($postRoleIdArr, $roleIdArr);
            $delRole = array_diff($roleIdArr, $postRoleIdArr);

            Db::startTrans();
            try{
                $user->save($post);
                if ($addRole) $user->roles()->saveAll($addRole);
                if ($delRole) $user->roles()->detach($delRole);
                Db::commit();
                $return = mkRestful(0, '编辑用户成功', 'success');
            } catch (Exception $e) {
                Db::rollback();
                $return = mkRestful(1, $e->getMessage());
            }

            return $return;
        }
        $roleIdArr = [];
        foreach ($user['roles'] as $role) {
            $roleIdArr[] = $role['id'];
        }
        $user['roleIdArr'] = $roleIdArr;
        $roles = RoleModel::where('disabled', 2)->select();

        $this->assign([
            'title' => '编辑用户',
            'user' => $user->getData(),
            'roles' => $roles
        ]);
        return $this->fetch();
    }

    // all
    public function all()
    {
        if ($this->request->isAjax()) {
            $get = $this->request->get();
            $users = UserModel::with('roles')->paginate($get['limit']);
            return mkTableRestful($users);
        }
        $users = UserModel::with('roles')->select();
        $this->assign([
            'title' => '用户管理',
            'users' => $users
        ]);
        return $this->fetch();
    }
    // detail
    public function detail($model = null)
    {
//        return parent::detail(UserModel::with('roles.privileges')); // TODO: Change the autogenerated stub

        $id = $this->request->param('id');
        $detail = UserModel::with('roles.privileges')->find($id)->toArray();

        // 获取角色
        $roles = $detail['roles'];

        // 取出该用户的所有角色与权限，合并所有角色的权限，去除不同角色中相同的权限
        $privileges = [];
        foreach ($roles as $role) {
            foreach ($role['privileges'] as $privilege) {
                $privileges[$privilege['id']] = $privilege;
            }
        }
        $detail['privileges'] = $privileges;

        if (!$detail) {
            return mkRestful(-1, '记录不存在');
        }
        $this->assign([
            'title' => '查看详情',
            'detail' => $detail
        ]);
        return $this->fetch();
    }
}